package com.kfm.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FileTransferServer {
    public static void main(String[] args) {
        // 服务器监听的端口
        int serverPort = 9999;

        try (ServerSocket serverSocket = new ServerSocket(serverPort)) {
            System.out.println("服务器正在监听端口 " + serverPort);

            while (true) {
                try (Socket socket = serverSocket.accept();
                     DataInputStream in = new DataInputStream(socket.getInputStream())) {

                    // 读取客户端发送的文件状态信息
                    String fileStatus = in.readUTF();
                    String filePath = in.readUTF();

                    // 如果是 "CREATED" 文件状态，处理文件创建事件
                    if ("CREATED".equals(fileStatus)) {
                        handleFileCreated(filePath);
                    }

                    // 读取文件名和文件大小
                    String fileName = in.readUTF();
                    long fileSize = in.readLong();
                    handleFileReception(fileName, fileSize, in);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 处理文件创建事件
    private static void handleFileCreated(String filePath) {
        // 处理文件创建事件的逻辑
        System.out.println("文件在服务器上创建：" + filePath);
        // 实现处理文件创建的具体逻辑。
    }

    // 处理接收的文件
    private static void handleFileReception(String fileName, long fileSize, DataInputStream in) {
        try {
            // 指定接收文件的路径
            File receivedFile = new File("D:\\kaifamiao\\notes\\temp" + fileName);
            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(receivedFile))) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead = 0;
                while (totalBytesRead < fileSize) {
                    bytesRead = in.read(buffer);
                    bos.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                }
                bos.flush();
                System.out.println("文件在服务器上接收成功：" + receivedFile.getAbsolutePath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
